package com.computergames.server.server.handler;

import com.computergames.server.message.LoginRequestMessage;
import com.computergames.server.message.LoginResponseMessage;
import com.computergames.server.server.session.SessionFactory;
import com.computergames.server.service.authentication.Interface.LoginService;
import com.computergames.server.util.SpringUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.AttributeKey;
import org.springframework.stereotype.Component;

@ChannelHandler.Sharable
@Component
public class LoginRequestMessageHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {

    private static final AttributeKey<String> USER_IDENTIFIER_KEY = AttributeKey.valueOf("USER_IDENTIFIER");
    //private static LoginRequestMessageHandler LoginRequestMessageHandler;
    //@Autowired
    LoginService loginService;


//    @PostConstruct
//    public void init() {
//        LoginRequestMessageHandler = this;
//    }

    @Override
    public void channelRead0(ChannelHandlerContext channelHandlerContext, LoginRequestMessage msg) throws Exception {
    loginService = SpringUtil.getBean(LoginService.class);
    String username = msg.getUsername();
    String hashedPassword = msg.getPassword();
    String token = loginService.GenerateToken(username, hashedPassword);
    if (token != null) {
        // 存储用户标识
        channelHandlerContext.channel().attr(USER_IDENTIFIER_KEY).set(username);
        SessionFactory.getSession().bind(channelHandlerContext.channel(), username);
        channelHandlerContext.writeAndFlush(new LoginResponseMessage(true, token, """
                            =============================================
                            \
                            请选择模式：
                            \
                            0 - 训练模式
                            \
                            1 - 比赛模式
                            \
                            =============================================
                            \s"""));
    } else {
        channelHandlerContext.writeAndFlush(new LoginResponseMessage(false, "用户名或密码错误"));
    }
}
}
